New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@placekit/client-js

Package Overview
Dependencies
Maintainers
2
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@placekit/client-js

PlaceKit JavaScript client

  • 2.3.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
918
increased by30.21%
Maintainers
2
Weekly downloads
 
Created
Source

PlaceKit JS Client

Location data, search and autocomplete for your apps

NPM LICENSE

FeaturesQuick startReferenceLicenseExamples


PlaceKit JavaScript Client abstracts interactions with our API, making your life easier. We highly recommend to use it instead of accessing our API directly.

👉 If you're looking for a full Autocomplete experience, have a look at our standalone PlaceKit Autocomplete JS library, or check out our examples to learn how to integrate with an existing components library.

✨ Features

  • Featherweight, zero-dependency HTTP client
  • Works both on the browser and node.js
  • Integrates with your preferred stack and autocomplete components (see examples)
  • TypeScript compatible

🎯 Quick start

NPM

First, install PlaceKit JavaScript Client using npm package manager:

npm install --save @placekit/client-js

Then import the package and perform your first address search:

// CommonJS syntax:
const placekit = require("@placekit/client-js/lite");

// ES6 Modules syntax:
import placekit from "@placekit/client-js/lite";

const pk = placekit("<your-api-key>", {
  //...
});

pk.search("Paris").then((res) => {
  console.log(res.results);
});

👉 Check out our examples for different use cases and advance usages!

CDN

First, add this line before the closing </body> tag in your HTML to import PlaceKit JavaScript Client:

<script src="https://cdn.jsdelivr.net/npm/@placekit/client-js@2.3.0/dist/placekit-lite.umd.js"></script>

Then it works the same as the node example above. After importing the library, placekit becomes available as a global:

<script>
  const pk = placekit("<your-api-key>", {
    //...
  });

  pk.search("Paris").then((res) => {
    console.log(res.results);
  });
</script>

Or if you are using native ES Modules:

<script type="module">
  import placekit from "https://cdn.jsdelivr.net/npm/@placekit/client-js@2.3.0/dist/placekit-lite.js";
  const pk = placekit(/* ... */);
  // ...
</script>

🧰 Reference

PlaceKit Client JS exports two versions of the client:

VersionPathMethodsModules
Lite@placekit/client-js/liteSearch methodsESM, CJS, UMD
Extended@placekit/client-jsAll methodsESM, CJS
  • Lite version has an optimized bundle size for the browser, but works also in the back-end.
  • Extended version methods require a private API key that you should never expose to the browser–it is intended for the back-end only.

Lite and Extended:

Extended-only:


placekit()

PlaceKit initialization function returns a PlaceKit client, named pk in all snippets below.

// Lite version, CommonJS syntax:
const placekit = require("@placekit/client-js/lite");

// Lite version, ES6 Modules syntax:
import placekit from "@placekit/client-js/lite";

// Extended version, CommonJS syntax:
const placekit = require("@placekit/client-js");

// Extended version, ES6 Modules syntax:
import placekit from "@placekit/client-js";

// Initialize PlaceKit client
const pk = placekit("<your-api-key>", {
  countries: ["fr"],
  language: "en",
  maxResults: 10,
});
ParameterTypeDescription
apiKeystringAPI key
optionskey-value mapping (optional)Global parameters (see options).

pk.search()

Performs a search and returns a Promise, which response is a list of results alongside some request metadata. The options passed as second parameter override the global parameters only for the current query.

pk.search("Paris", {
  countries: ["fr"],
  maxResults: 5,
}).then((res) => {
  console.log(res.results);
});
ParameterTypeDescription
querystringSearch terms
optskey-value mapping (optional)Search-specific parameters (see options).

pk.reverse()

Performs a reverse geocoding search and returns a Promise, which response is a list of results alongside some request metadata. The options passed as first parameter override the global parameters only for the current query. Any coordinates previously set as option would be overriden by the coordinates passed as first argument.

pk.reverse({
  coordinates: "48.871086,2.3036339",
  countries: ["fr"],
  maxResults: 5,
}).then((res) => {
  console.log(res.results);
});
ParameterTypeDescription
optskey-value mapping (optional)Search-specific parameters (see options).

Notes:

  • If you omit options.coordinates, it'll use coordinates from global parameters set when instanciating with placekit() or with pk.configure().

pk.options

Read-only to access global options persistent across all API calls that are set at initialization and with pk.configure(). Options passed at query time in pk.search() override global parameters only for that specific query.

console.log(pk.options); // { "language": "en", "maxResults": 10, ... }
OptionTypeDefaultDescription
countriesstring[]?undefinedCountries to search in, default to current IP country. Array of two-letter ISO country codes(1).
languagestring?undefinedPreferred language for the results(1), two-letter ISO language code. Supported languages are en and fr. By default the results are displayed in their country's language.
typesstring[]?undefinedType of results to show. Array of accepted values: street, city, country, administrative, airport, bus, county, train, townhall, tourism. Prepend - to omit a type like ['-bus']. Unset to return all.
maxResultsinteger?5Number of results per page.
coordinatesstring?undefinedCoordinates to search around. Automatically set when calling pk.requestGeolocation().
forwardIPstring?undefinedSet x-forwarded-for header to forward the provided IP for back-end usages (otherwise it'll use the server IP).

[1]: See Coverage for more details.

pk.configure()

Updates global parameters. Returns void.

pk.configure({
  language: "fr",
  maxResults: 5,
});
ParameterTypeDescription
optskey-value mapping (optional)Global parameters (see options)

pk.requestGeolocation()

Requests device's geolocation (browser-only). Returns a Promise with a GeolocationPosition object.

pk.requestGeolocation({ timeout: 10000 }).then((pos) =>
  console.log(pos.coords)
);
ParameterTypeDescription
optskey-value mapping (optional)navigator.geolocation.getCurrentPosition options.

The location will be store in the coordinates global options, you can still manually override it.

pk.clearGeolocation()

Clear device's geolocation stored with pk.requestGeolocation.

pk.clearGeolocation();

The global option coordinates will be deleted and pk.hasGeolocation will be set to false.

pk.hasGeolocation

Reads if device geolocation is activated or not (read-only).

console.log(pk.hasGeolocation); // true or false

pk.patch.list()

⚠️ Restricted to private API keys, do NOT expose the private key to the browser.

List, filter and paginate patch records.

// get all patches, paginated
pk.patch.list().then((res) => {
  console.log(res.results);
});

// filter and paginate patches
pk.patch
  .list({
    status: "approved",
    maxResults: 10,
    offset: 10,
  })
  .then((res) => {
    console.log(res.results);
  });
ParameterTypeDescription
optskey-value mapping (optional)Search options.
opts.status('pending' | 'approved')?Publication status.
opts.querystring?Terms filter.
opts.countriesstring[]?Countries filter, array of two-letter ISO country codes.
opts.typesstring[]?Types filter, array of accepted values: street, city, administrative, airport, bus, county, train, townhall, tourism. Prepend - to omit a type like ['-bus']. Unset to return all.
opts.languagestring?undefined
opts.maxResultsnumber?Maximum number of results to return.
opts.offsetnumber?Paginate results starting from the offset.
Patch Record status explained
  • pending: only available through Live Patching endpoints,
  • approved: available to end-users through Search endpoints.

pk.patch.create()

⚠️ Restricted to private API keys, do NOT expose the private key to the browser.

Add a missing location or fix an existing one.

// Adding a missing location
const record = {
  type: 'street',
  name: 'New street',
  city: 'Los Angeles',
  county: 'Los Angeles',
  administrative: 'California',
  country: 'United States of America',
  countrycode: 'us',
  coordinates: '33.9955095,-118.472482',
  zipcode: ['90291'],
  population: 3849000,
};
pk.patch.create(record, { status: 'approved' }).then((record) => {
  console.log(record);
});

// Fixing an existing location
pk.patch.create(
  { population: 3849000 },
  { status: 'approved' }
  originalRecord, // original record from `pk.search` or `pk.reverse`
).then((record) => {
  console.log(record);
});
ParameterTypeDescription
updatekey-value mappingFull patch record if adding, at least one property if fixing.
update.typestringRecord type, one of administrative, airport, bus, city, county, street, tourism, townhall, train.
update.namestringRecord display name (street name, city name, station name...).
update.citystringRecord city name.
update.countystring (optional)Record county/province/department.
update.administrativestring (optional)Record administrative/region/state.
update.countrystringRecord country name.
update.countrycodestringRecord two-letter ISO country code.
update.coordinatesstringRecord coordinates in format lat,lng.
update.zipcodestring[]Record postal/zip code(s).
update.populationnumberRecord population of its city.
optskey-value mapping (optional)Patch record options.
opts.status('pending' | 'approved')?Record status.
opts.languagestring?Language in which the record is written, two-letter ISO language code.
originkey-value mapping (optional)Original (and complete) record to fix, from pk.search() or pk.reverse().
Patch Record language explained

Language is always considered as "preferred display language", which means:

  • If you omit opts.language, then details will be set in the default language.
  • If the patch record has a translation but no default, then the first available translation will be used as default.
  • If the patch record misses some translation, it will show the default value for non-translated properties.

pk.patch.get()

⚠️ Restricted to private API keys, do NOT expose the private key to the browser.

Retrieve a patch record by ID.

// get record default language
pk.patch.get("<patch-id>").then((record) => {
  console.log(record);
});

// get record FR translation
pk.patch.get("<patch-id>", "fr").then((record) => {
  console.log(record);
});
ParameterTypeDescription
idstringRecord ID.
languagestring?Language to get, two-letter ISO language code.

pk.patch.update()

⚠️ Restricted to private API keys, do NOT expose the private key to the browser.

Update a patch record.

// update and publish
pk.patch
  .update(
    "<patch-id>",
    { coordinates: "33.9955095,-118.472482" },
    { status: "approved" }
  )
  .then((record) => {
    console.log(record);
  });

// update translation
pk.patch
  .update("<patch-id>", { name: "Rue Nouvelle" }, { language: "fr" })
  .then((record) => {
    console.log(record);
  });

// unpublish
pk.patch
  .update("<patch-id>", undefined, { status: "pending" })
  .then((record) => {
    console.log(record);
  });
ParameterTypeDescription
idstringRecord ID.
updatekey-value mapping (optional)Updated fields, at least one property must be set if defined.
update.typestringOne of administrative, airport, bus, city, county, street, tourism, townhall, train.
update.namestringRecord display name (street name, city name, station name...).
update.citystringRecord city name.
update.countystring (optional)Record county/province/department.
update.administrativestring (optional)Record administrative/region/state.
update.countrystringRecord country name.
update.countrycodestringRecord two-letter ISO country code.
update.coordinatesstringRecord coordinates in format lat,lng.
update.zipcodestring[]Record postal/zip code(s).
update.populationnumberRecord population of its city.
optskey-value mapping (optional)Patch options.
opts.status('pending' | 'approved')?Publication status.
opts.languagestring?Target language, two-letter ISO language code.

pk.patch.delete()

⚠️ Restricted to private API keys, do NOT expose the private key to the browser.

Delete a patch record.

pk.patch.delete("<patch-id>");
ParameterTypeDescription
idstringRecord ID.

pk.patch.deleteLang()

⚠️ Restricted to private API keys, do NOT expose the private key to the browser.

Delete a patch translation.

pk.patch.deleteLang("<patch-id>", "fr");
ParameterTypeDescription
idstringRecord ID.
languagestringLanguage to unset, two-letter ISO language code.

NOTES:

  • Deleting a translation will return a 409 error if there is no default language and no other translation available.

pk.keys.list()

⚠️ Restricted to private API keys, do NOT expose the private key to the browser.

Retrieve all application API keys.

pk.keys.list();

pk.keys.create()

⚠️ Restricted to private API keys, do NOT expose the private key to the browser.

Create an application API key.

pk.keys.create("<role>", { domains: [] });
ParameterTypeDescription
role('public' | 'private')API key role.
optionsobject?API key options.
options.domainsstring[]?Domain restriction.

pk.keys.get()

⚠️ Restricted to private API keys, do NOT expose the private key to the browser.

Retrieve an API key by ID.

pk.keys.get("<key-id>");
ParameterTypeDescription
idstringAPI key ID.

pk.keys.update()

⚠️ Restricted to private API keys, do NOT expose the private key to the browser.

Update an API key.

pk.keys.update("<key-id>", { domains: [] });
ParameterTypeDescription
idstringAPI key ID.
optionsobject?API key options.
options.domainsstring[]?Domain or IP restriction (for public keys only).

pk.keys.delete()

⚠️ Restricted to private API keys, do NOT expose the private key to the browser.

Delete an API key.

pk.keys.delete("<key-id>");
ParameterTypeDescription
idstringAPI key ID.

⚖️ License

PlaceKit JavaScript Client is an open-sourced software licensed under the MIT license.

Keywords

FAQs

Package last updated on 23 Feb 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc